package zld369504.tw.m_team;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.Response;
import okhttp3.ResponseBody;
import zld369504.tw.m_team.api.MTeamHttpsApi;
import zld369504.tw.m_team.api.MTeamHttpsApiImpl;
import zld369504.tw.m_team.fragments.MainFragment;
import zld369504.tw.m_team.fragments.SlideMenuFragment;
import zld369504.tw.m_team.fragments.TorrentListFragment;

public class MainActivity extends BaseActivity {

    private Toolbar toolbar;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;

    private MyReceiver receiver;
    private String currentFragmentTag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(getResources().getString(R.string.menu_string_home));

        receiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("tw.zld369504.m-team.MainNavigationViewItemSelected");
        LocalBroadcastManager mgr = LocalBroadcastManager.getInstance(this);
        mgr.registerReceiver(receiver, filter);

        boolean needReload = getIntent().getBooleanExtra("needLoadIndexPage", false);
        if (needReload) {
            MTeamHttpsApi api = MTeamHttpsApiImpl.getInstance();
            api.getMainPage(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showErrorDialog("请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    int responseCode = response.code();
                    if (responseCode == 200) {
                        ResponseBody body = response.body();
                        DataParser.parseUserBriefInfoFromMainPageSide(body.string());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                loadView();
                            }
                        });
                    } else if (responseCode == 302) {
                        Headers headers = response.headers();
                        List<String> valueList = headers.values("Location");
                        boolean check = false;
                        for (String s : valueList) {
                            if ((MTeamHttpsApiImpl.baseUrl + "/login.php").equals(s)) {
                                check = true;
                                break;
                            } else {
                                check = false;
                            }
                        }
                        if (check) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                                    finish();
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showErrorDialog("出现了一个问题。302跳转url是一个没有被处理的url");
                                }
                            });
                        }
                    }
                }
            });
        } else {
            loadView();
        }
    }

    private void loadView() {
        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);

        mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
        mDrawerToggle.syncState();
        drawerLayout.addDrawerListener(mDrawerToggle);

        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        loadDefaultFragment();
        loadSlideMenuFragment();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        drawerLayout.removeDrawerListener(mDrawerToggle);
        LocalBroadcastManager mgr = LocalBroadcastManager.getInstance(this);
        mgr.unregisterReceiver(receiver);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                drawerLayout.openDrawer(GravityCompat.START);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void loadDefaultFragment() {
        MainFragment mainFragment = MainFragment.newInstance();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragmentContainer, mainFragment, currentFragmentTag = MainFragment.TAG);
        transaction.commit();
    }

    private void loadSlideMenuFragment() {
        SlideMenuFragment fragment = SlideMenuFragment.newInstance();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.slideMenuContainer, fragment, MainFragment.TAG);
        transaction.commit();
    }

    private void loadFunctionFragment(int menuId, String menuTitle, String fragmentTag) {
        toolbar.setTitle(menuTitle);
        drawerLayout.closeDrawer(GravityCompat.START, true);
        if (fragmentTag.equals(currentFragmentTag)) {
            return;
        }
        if (menuId == R.id.menu_home) {
            loadDefaultFragment();
            return;
        }
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        switch (menuId) {
            case R.id.menu_adult:
                transaction.replace(R.id.fragmentContainer, TorrentListFragment.getInstance(3), currentFragmentTag = TorrentListFragment.adult);
                break;
            case R.id.menu_comprehensive:
                transaction.replace(R.id.fragmentContainer, TorrentListFragment.getInstance(1), currentFragmentTag = TorrentListFragment.comprehensive);
                break;
            case R.id.menu_four_k:
                transaction.replace(R.id.fragmentContainer, TorrentListFragment.getInstance(2), currentFragmentTag = TorrentListFragment.fourK);
                break;
        }
        transaction.commit();
    }

    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("tw.zld369504.m-team.MainNavigationViewItemSelected".equals(action)) {
                int menuId = intent.getIntExtra("menu_id", 0);
                String menuTitle = intent.getStringExtra("menu_title");
                String fragmentTag = intent.getStringExtra("fragmentTag");
                loadFunctionFragment(menuId, menuTitle, fragmentTag);
            }
        }
    }
}
